package com.cjy.runnable.demo11;

/**
 * @author Cheng JiYe
 * @description:
 * @date 2021/4/25 1:48
 */
public class ThreadDeadLock implements Runnable {
  /** 实例化static型对象 */
  private static Zhangsan zs = new Zhangsan();

  /** 实例化static型对象 */
  private static Lisi ls = new Lisi();

  /** 声明标志位，判断那个先说话 */
  private boolean flag = false;

  /** 覆写run()方法 */
  @Override
  public void run() {
    if (flag) {
      // 同步张三
      synchronized (zs) {
        zs.say();
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized (ls) {
          zs.get();
        }
      }
    } else {
      synchronized (ls) {
        ls.say();
        try {
          Thread.sleep(500);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        synchronized (zs) {
          ls.get();
        }
      }
    }
  }

  public static void main(String args[]) {
    ThreadDeadLock t1 = new ThreadDeadLock(); // 控制张三
    ThreadDeadLock t2 = new ThreadDeadLock(); // 控制李四
    t1.flag = true;
    t2.flag = false;
    Thread thA = new Thread(t1);
    Thread thB = new Thread(t2);
    thA.start();
    thB.start();
  }
}
